﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.DirectoryServices;

using groupAnalyzer.connectivity;
using groupAnalyzer.model;

namespace groupAnalyzer.controller
{
    class Expander
    {
        private LdapConnectivity ldapConnectivity;
        private string baseDN;
        private Factory factory;

        private Container root;

        private Dictionary<string, AbstractElementLdap> elements;

        private void build(DirectoryEntry father, Container fatherContainer)
        {
            foreach (DirectoryEntry childs in father.Children)
            {
                string fqdn =ldapConnectivity.getProperty(childs,"distinguishedName",0);
                string name = ldapConnectivity.getProperty(childs, "name", 0);

                switch (childs.SchemaClassName.ToString())
                {
                    case "group":                 
                        fatherContainer.addChild(this.factory.constructGroup(name,fqdn));
                        break;
                    case "user":
                        string department = ldapConnectivity.getProperty(childs,"department",0);
                        string email = ldapConnectivity.getProperty(childs,"mail",0);
                        fatherContainer.addChild(this.factory.constructUser(name, department, email, fqdn));
                        break;

                    case "container":
                    case "organizationalUnit":
                        Container container = this.factory.constructContainer(name, fqdn);
                        fatherContainer.addChild(container);
                        this.build(childs, container);
                        break;

                    default:

                        break;
                }
            }
        }

        public void build()
        {
            // cache!
            if (this.root == null)
            {
                DirectoryEntry rootEntry = this.ldapConnectivity.getRoot();
                this.root = this.factory.constructRootContainer("test.home", "dc=test,dc=home");
                
                this.build(rootEntry, root);
            }
        }

        public void reset()
        {
            this.elements.Clear();
            this.root = null;
        }

        public Expander(LdapConnectivity ldapConnectivity, string baseDN, Factory factory)
        {
            this.ldapConnectivity = ldapConnectivity;
            this.baseDN = baseDN;
            this.factory = factory;

            this.root = null;
            this.elements = new Dictionary<string, AbstractElementLdap>();
        }
    }
}
